package com.iteaj.iot.client.component;

import com.iteaj.iot.client.TcpSocketClient;
import com.iteaj.iot.*;
import com.iteaj.iot.client.ClientComponent;
import com.iteaj.iot.client.ClientMessage;
import com.iteaj.iot.client.IotClient;
import com.iteaj.iot.client.MultiClientManager;
import com.iteaj.iot.codec.IotMessageDecoder;
import com.iteaj.iot.config.ConnectProperties;
import io.netty.channel.nio.NioEventLoopGroup;

import java.util.Collection;

/**
 * 此适配器可以自定义实现各个组件的实现细节
 * 只能使用单客户端
 * @see MultiClientManager 无效
 * @param <M>
 */
public abstract class SingleTcpClientComponent<M extends ClientMessage> extends TcpSocketClient
        implements IotProtocolFactory<M>, ClientComponent<M> {

    private ProtocolFactory<M> delegation;

    public SingleTcpClientComponent(ConnectProperties config) {
        super(null, config);
        this.setClientComponent(this);
        this.delegation = new ProtocolFactoryDelegation(this, new ProtocolTimeoutStorage(getDesc()));
    }

    @Override
    public void addClient(Object clientKey, IotClient value) { }

    @Override
    public IotClient getClient(Object clientKey) {
        return this;
    }

    @Override
    public IotClient removeClient(Object clientKey) { return null; }

    @Override
    public Collection<IotClient> clients() {
        return null;
    }

    @Override
    public final void init(NioEventLoopGroup clientGroup) {
        super.init(clientGroup);
    }

    @Override
    public void connect() {
        this.getClient().connect(null, 3000);
    }

    /**
     * 默认使用单客户端, 需要多客户端请自行覆写实现
     * @param config
     * @return
     */
    @Override
    public TcpSocketClient createNewClient(ConnectProperties config) {
        return this;
    }

    @Override
    public abstract String getName();

    @Override
    public AbstractProtocol get(String key) {
        return delegation.get(key);
    }

    @Override
    public AbstractProtocol add(String key, Protocol val) {
        return delegation.add(key, val);
    }

    @Override
    public AbstractProtocol add(String key, Protocol protocol, long timeout) {
        return delegation.add(key, protocol, timeout);
    }

    @Override
    public AbstractProtocol remove(String key) {
        return delegation.remove(key);
    }

    @Override
    public boolean isExists(String key) {
        return delegation.isExists(key);
    }

    @Override
    public Object getStorage() {
        return delegation.getStorage();
    }

    @Override
    protected abstract IotMessageDecoder createProtocolDecoder();

    @Override
    public String getDesc() {
        return "Tcp客户端组件("+this.getClass().getSimpleName()+")";
    }

    @Override
    public void init(Object... args) {
        super.init((NioEventLoopGroup) args[0]);
    }

    @Override
    public TcpSocketClient getClient() {
        return this;
    }

    @Override
    public IotProtocolFactory protocolFactory() {
        return this.delegation;
    }

}
